<template>
  <!-- 拍照搜题操作教程页面 -->
  <NavBar title="拍照搜题" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="photo-search-container">
	   <view class="main-content">
		 <image class="tishi" :src="searchBannerUrl" mode="scaleToFill"></image>
	   </view>
<!--    <view class="main-content">
      <view class="tips-grid">
        <view class="tips-row">
          <view class="tip-card wrong-tip">
            <view class="phone-demo">
              <image class="phone-demo-img" src="/static/search1.png" mode=""></image>
            </view>
            <button class="tip-button wrong-button">禁止横拍</button>
          </view>

          <view class="tip-card wrong-tip">
            <view class="phone-demo">
              <image class="phone-demo-img" src="/static/search8.png" mode=""></image>
            </view>
            <button class="tip-button wrong-button">禁止斜拍</button>
          </view>
        </view>

        <view class="tips-row">
          <view class="tip-card wrong-tip">
            <view class="phone-demo">
 <image class="phone-demo-img" src="/static/search3.png" mode=""></image>
            </view>
            <button class="tip-button wrong-button">禁止个性化文字</button>
          </view>

          <view class="tip-card wrong-tip">
            <view class="phone-demo">
   <image class="phone-demo-img" src="/static/search2.png" mode=""></image>
            </view>
            <button class="tip-button wrong-button">禁止背景有其他文字干扰</button>
          </view>
        </view>
        <view class="tips-row">
          <view class="tip-card correct-tip">
            <view class="phone-demo">
        <image class="phone-demo-zc" src="/static/search4.png" mode=""></image>
            </view>
            <button class="tip-button correct-button">注意光线、不要遮挡、垂直正对、对焦清晰</button>
          </view>
        </view>
      </view>
    </view> -->
    
    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <view class="action-item" @click="chooseFromAlbum">
        <image class="action-icon" src="/static/update2.png" mode=""></image>
        <text class="action-text">相册选图</text>
      </view>
      <view class="divider"></view>
      <view class="action-item" @click="takePhoto">
        <image class="action-icon" src="/static/update1.png" mode=""></image>
        <text class="action-text">拍照搜题</text>
      </view>
    </view>

      <uni-popup 
   ref="insufficientPopup" type="center" :mask-click="false"
  >
    <view class="popup-container">
      <!-- 背景图片 -->
      <image 
        class="popup-bg" 
        src="/static/commonPopup1.png" 
        mode="aspectFill"
      />
      
      <!-- 右上角图标 -->
      <view class="popup-icon">
        <image 
           src="/static/commonTitle.png" 
          class="icon-image"
        />
      </view>
      
      <!-- 弹窗内容 -->
      <view class="popup-content">
        <!-- 主标题 -->
        <view class="popup-title">拍照次数不足</view>
        
        
        <!-- 内容区域 -->
        <view class="popup-message">当前剩余拍照搜题次数不足 请购买后使用！</view>
        
        <!-- 按钮区域 -->
        <view class="popup-buttons">
          <button 
            class="popup-btn cancel-btn" 
           @click="closeInsufficientModal"
          >
            取消
          </button>

           <button 
            class="popup-btn  purchase-btn " 
           @click="goToPurchase"
          >
            去购买
          </button>
        </view>
      </view>
    </view>
  </uni-popup>


    <!-- 登录弹窗组件 -->
    <LoginModal 
      ref="loginModalRef"
      @close="onLoginModalClose"
      @skip="onLoginSkip"
      @login="onLoginSuccess"
    />
    
  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import LoginModal from '@/components/LoginModal/LoginModal.vue'
import { isLoggedIn, getCurrentUser, navigateToLogin } from '../../utils/user.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'
import { getPostersConfig } from '../../utils/config.js'

// 响应式数据
const currentTime = ref('')
const hasPhoto = ref(false)
const photoPath = ref('')
const searchBannerUrl = ref('') // 默认图片

// uni-popup引用
const insufficientPopup = ref()
const loginModalRef = ref()
const searchHistory = ref([
  {
    question: '求函数f(x)=x²+2x+1的最小值',
    time: '10:30'
  },
  {
    question: '解方程2x+3=7',
    time: '09:15'
  }
])

// 获取公共配置中的搜索横幅图片
const fetchSearchBanner = async () => {
  try {
    const postersConfig = await getPostersConfig()
    if (postersConfig?.search_banner) {
      searchBannerUrl.value = postersConfig.search_banner
      console.log('搜索横幅图片更新:', searchBannerUrl.value)
    }
  } catch (error) {
    console.error('获取搜索横幅图片失败:', error)
    // 保持使用默认图片
  }
}

// 页面加载时获取当前时间
onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  // 获取搜索横幅图片
  fetchSearchBanner()
})

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    hour12: false 
  })
}

// 拍照功能
const takePhoto = () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/photo-search/photo-search')
    }
    return
  }
  
  // 检查拍照次数
  if (!checkPhotoAttempts()) {
    insufficientPopup.value.open()
    return
  }
  
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['camera'],
    success: (res) => {
      console.log('拍照成功:', res)
      photoPath.value = res.tempFilePaths[0]
      hasPhoto.value = true

      // 跳转到拍照进行中页面，传递文件路径参数
      uni.navigateTo({
        url: `/pages/photo-progress/photo-progress?filePath=${encodeURIComponent(res.tempFilePaths[0])}`
      });
    },
    fail: (err) => {
      console.error('拍照失败:', err)
      uni.showToast({
        title: '拍照失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 相册选图功能
const chooseFromAlbum = () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/photo-search/photo-search')
    }
    return
  }
  
  // 检查拍照次数
  if (!checkPhotoAttempts()) {
    insufficientPopup.value.open()
    return
  }
  
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      console.log('选择图片成功:', res)
      photoPath.value = res.tempFilePaths[0]
      hasPhoto.value = true

      // 跳转到拍照进行中页面，传递文件路径参数
      uni.navigateTo({
        url: `/pages/photo-progress/photo-progress?filePath=${encodeURIComponent(res.tempFilePaths[0])}`
      });
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    success: () => {
      console.log('返回成功')
    },
    fail: (err) => {
      console.error('返回失败:', err)
      // 如果返回失败，跳转到首页
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  })
}

// 重新拍照
const retakePhoto = () => {
  hasPhoto.value = false
  photoPath.value = ''
}

// 开始搜题
const searchQuestion = () => {
  if (!hasPhoto.value) {
    uni.showToast({
      title: '请先拍照',
      icon: 'none'
    })
    return
  }
  
  // 跳转到拍照进行中页面
  uni.navigateTo({
    url: '/pages/photo-progress/photo-progress'
  })
}

// 从历史记录搜索
const searchFromHistory = (item: any) => {
  uni.showToast({
    title: `搜索: ${item.question}`,
    icon: 'none',
    duration: 2000
  })
}



// 显示登录弹窗
const showLoginModal = () => {
  loginModalRef.value.open()
}

// 检查拍照次数
const checkPhotoAttempts = () => {
  try {
    // 获取当前用户信息
    const currentUser = getCurrentUser()

    if (!currentUser) {
      console.log('用户信息不存在')
      return false
    }

    // 检查pkg_credit字段是否大于0
    const pkgCredit = currentUser.pkg_credit || 0
    console.log('当前用户拍照次数:', pkgCredit)

    return pkgCredit > 0
  } catch (error) {
    console.error('检查拍照次数失败:', error)
    return false
  }
}

// 弹窗控制方法
const closeInsufficientModal = () => {
  insufficientPopup.value.close()
}

const goToPurchase = () => {
  closeInsufficientModal()
  uni.navigateTo({ url: '/pages/purchase-resource/purchase-resource' })
}

// 登录弹窗事件处理
const onLoginModalClose = () => {
  console.log('登录弹窗关闭')
}

const onLoginSkip = () => {
  uni.showToast({
    title: '暂不登录',
    icon: 'none',
    duration: 2000
  })
}

const onLoginSuccess = () => {
  //弹框处理了登录逻辑 这里只处理登录完成逻辑
}
</script>

<style scoped>
.photo-search-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #C2DDFF 0%, #FFFFFF 100%);
  padding-top: 160rpx;
}
.popup-container {
  position: relative;
  width: 600rpx;
   height: 570rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
}
.popup-icon {
  position: absolute;
  top: 120rpx;
  left: 35rpx;
  width: 186rpx;
  height: 26rpx;
  z-index: 3;
}
.popup-bg {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 570rpx;
  z-index: 1;
}

.icon-image {
 width: 186rpx;
 height: 26rpx;
 background-size: 100% 100%;
}

.phone-demo-img {
  width: 240rpx;
  height: 260rpx;
  border-radius: 12rpx;
  object-fit: cover;
}
/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
  position: sticky;
  top: 0;
  z-index: 100;
}
.tishi{
	width: 602rpx;
	height: 1208rpx;
}
.status-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.back-arrow {
  font-size: 40rpx;
  color: #333;
  font-weight: bold;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #1A1A1A;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.app-icono-img{
	width: 122rpx;
	height: 122rpx;
}
.status-center {
  flex: 1;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #1A1A1A;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #1A1A1A;
  opacity: 0.8;
}

/* 主要内容区域 */
.main-content {
  margin: 30rpx;
  background: white;
  border-radius: 16rpx;
  padding: 40rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 1210rpx;
}

/* 提示网格 */
.tips-grid {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.tips-row {
  display: flex;
  gap: 20rpx;
  justify-content: center;
}

.tip-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}
.phone-demo-zc{
	width: 332rpx;
	height: 356rpx;
}
.phone-demo {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  
}

.phone-horizontal {
  width: 80rpx;
  height: 120rpx;
  background: #f0f0f0;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotate(90deg);
}

.phone-tilted {
  width: 60rpx;
  height: 100rpx;
  background: #f0f0f0;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotate(15deg);
}

.phone-vertical {
  width: 60rpx;
  height: 100rpx;
  background: #f0f0f0;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.phone-screen {
  font-size: 24rpx;
}

.wrong-mark {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  font-size: 40rpx;
  color: #ff4444;
  font-weight: bold;
}

.correct-mark {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  font-size: 40rpx;
  color: #00aa00;
  font-weight: bold;
}
.popup-message {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 50rpx;
  padding: 0 20rpx;
  margin-top: 140rpx;
}

.tip-button {
  padding: 12rpx 15rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 600;
  border: none;
  text-align: center;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15rpx;
}

.wrong-button {
  background: #ff4444;
  color: white;
}

.correct-button {
  background: #00aa00;
  color: white;
}

/* 底部操作按钮 */
.bottom-actions {
  position: fixed;
  bottom: 20rpx;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
}

.action-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  gap: 8rpx;
  transition: all 0.3s ease;
}

.action-icon {
 width: 65rpx;
 height: 65rpx;
 margin-right: 15rpx;
}

.action-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.divider {
  width: 2rpx;
  height: 60rpx;
  background: #B2B2B2;
}

/* 底部指示条 */
.bottom-indicator {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 8rpx;
  background: #000;
  border-radius: 4rpx;
  margin-bottom: 10rpx;
}

.modal-header {
  text-align: center;
  margin-bottom: 40rpx;
  position: relative;
  animation: slideInDown 0.6s ease-out 0.2s both;
}

.modal-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
  animation: fadeInUp 0.5s ease-out 0.3s both;
}

.modal-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
  margin-bottom: 30rpx;
  animation: fadeInUp 0.5s ease-out 0.4s both;
}

.modal-icon {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
  gap: 8rpx;
  animation: bounceIn 0.8s ease-out 0.5s both;
}

.icon-phone {
  font-size: 32rpx;
  background: #E3F2FD;
  padding: 8rpx;
  border-radius: 8rpx;
}

.icon-chart {
  font-size: 24rpx;
  background: #E8F5E8;
  padding: 8rpx;
  border-radius: 8rpx;
}

.icon-arrow {
  font-size: 20rpx;
  background: #FFF3E0;
  padding: 8rpx;
  border-radius: 8rpx;
}

.modal-body {
  text-align: center;
  margin-bottom: 40rpx;
  animation: fadeInUp 0.5s ease-out 0.6s both;
}
.popup-content {
  position: relative;
  z-index: 2;
  padding: 60rpx 40rpx 40rpx;
  text-align: center;
  height: 75%;
}

.popup-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #000;
  margin-bottom: 46rpx;
  line-height: 1.4;
  text-align: left;
}

.modal-message {
  font-size: 32rpx;
  color: #333;
  line-height: 1.5;
}
.popup-buttons {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 90%;
  transform: translateX(-50%);
  
}

.popup-btn {
  width: 44%;
  height: 80rpx;
  border-radius: 38rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  outline: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  color: #fff;
}
.modal-actions {
  display: flex;
  gap: 20rpx;
  animation: fadeInUp 0.5s ease-out 0.7s both;
}

.modal-btn {
  flex: 1;
  border-radius: 60rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  height: 80rpx;
  line-height:80rpx;
}

.cancel-btn {
  background: #F5F5F5;
  color: #BFBFBF;
  font-size: 28rpx;
  border: 2rpx solid #F5F5F5;
}

.cancel-btn:active {
  transform: translateY(2rpx) scale(0.98);
  background: #f5f5f5;
}
.cancel-btn:after{
  border:none;
}
.purchase-btn {
  background: #007AFF;
  color: white;
  position: relative;
}

.purchase-btn:active {
  transform: translateY(2rpx) scale(0.98);
  background: #0056CC;
}

.purchase-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.purchase-btn:active::before {
  left: 100%;
}


/* 拍照搜题弹窗 - uni-popup内容 */
.photo-search-popup-content {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx;
  position: relative;
  width: 100%;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}


.popup-close {
  font-size: 40rpx;
  color: #666;
  font-weight: bold;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.popup-close:active {
  transform: scale(0.9);
  color: #333;
}

/* 拍照区域 */
.camera-section {
  margin-bottom: 30rpx;
}

.camera-container {
  position: relative;
  height: 400rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  overflow: hidden;
}

.camera-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-placeholder {
  text-align: center;
  padding: 40rpx;
}

.camera-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
  opacity: 0.6;
}

.camera-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.camera-hint {
  font-size: 24rpx;
  color: #666;
  display: block;
  line-height: 1.4;
}

.photo-preview {
  width: 100%;
  height: 100%;
  position: relative;
}

.captured-photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 30rpx;
}

.photo-actions {
  display: flex;
  gap: 20rpx;
  justify-content: center;
}

.action-btn {
  padding: 16rpx 32rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
}

.retake-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #666;
}

.search-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.action-btn:active {
  transform: translateY(2rpx);
}

/* 弹窗操作按钮 */
.popup-actions {
  display: flex;
  gap: 20rpx;
}

.popup-action-btn {
  flex: 1;
  padding: 24rpx 0;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.album-btn {
  background: #f5f5f5;
  color: #666;
}

.camera-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.popup-action-btn:active {
  transform: translateY(2rpx) scale(0.98);
}

.btn-icon {
  font-size: 32rpx;
}

.btn-text {
  font-size: 24rpx;
}


/* 关键帧动画 */
@keyframes slideInDown {
  from {
    transform: translateY(-50rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    transform: translateY(30rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes bounceIn {
  0% {
    transform: scale(0.3);
    opacity: 0;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

/* 图标动画 */
.icon-phone, .icon-chart, .icon-arrow {
  animation: pulse 2s ease-in-out infinite;
}

.icon-phone {
  animation-delay: 0s;
}

.icon-chart {
  animation-delay: 0.2s;
}

.icon-arrow {
  animation-delay: 0.4s;
}
</style>
